package pl.edu.agh.logview;

import javax.swing.JFrame;

import pl.edu.agh.logview.graph.GraphManager;
import pl.edu.agh.logview.model.Edge;
import pl.edu.agh.logview.model.Vertex;
import pl.edu.agh.logview.webservice.Server;

import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;

public class App extends JFrame { 

	private static final long serialVersionUID = 1L;

	private GraphManager graphManager;
	private mxGraph graph;
	private mxGraphComponent graphComponent;
	private Object parent;
	
	public App() {
		graph = new mxGraph();
		parent = graph.getDefaultParent();
		graph.setEnabled(false);
		graph.setCellsLocked(true);
		graph.setCellsSelectable(false);
		graphManager = new GraphManager();
		prepareGraph();
		graphComponent = new mxGraphComponent(graph);
		getContentPane().add(graphComponent);
	}
	
	private void prepareGraph() {
		graph.getModel().beginUpdate();
		try {
			if(graphManager == null)
				return;
			for (Vertex vertex : graphManager.getAllVertices() ) {
				vertex.setVertexObject( graph.insertVertex(parent, null, vertex.getName(), vertex.getX(),
						vertex.getY(), vertex.getVertexType().getWidth(),  vertex.getVertexType().getHeight()) );
				System.out.println("Dodano vertex");
			}
			
			for (Edge e : graphManager.getAllEdges() ) {
				e.setGraphEdge( graph.insertEdge(parent, null, e.getMessage(), e.from().getVertexObject(), e.to().getVertexObject(), e.getEdgeType().getStyle() ) );
				System.out.println("dodano krawedz");
			}
//			
//			for (Vertex vertex : graphManager.getAxis() ) {
//				vertex.setVertex( graph.insertVertex(parent, null, vertex.getMessage(), vertex.getX(),
//						vertex.getY(), vertex.getType().getWidth(),  vertex.getType().getHeight()) );
//			}
		}
		catch(Exception e ){
			e.printStackTrace();			
		}
		finally {
		   graph.getModel().endUpdate();
		}
	}
	
	private void refresh() {
		while (true){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			prepareGraph();
			graphComponent = new mxGraphComponent(graph);
			getContentPane().add(graphComponent);
		}
	}
	
	public static void main(String[] argv) {
		Server server = new Server();
		
		App frame = new App();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(800, 820);
		frame.setVisible(true);
		frame.refresh();
		
		
	}


	
}
